package com.meiyuetao.myt.md.web.action;

import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.md.entity.GiftPaper;
import com.meiyuetao.myt.md.entity.GiftPaperObject;
import com.meiyuetao.myt.md.service.GiftPaperObjectService;
import com.meiyuetao.myt.md.service.GiftPaperService;
import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.view.OperationResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.eclipse.jetty.util.security.Credential.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@MetaData("GiftPaperController")
public class GiftPaperController extends MytBaseController<GiftPaper, Long> {

    @Autowired
    private GiftPaperService giftPaperService;
    @Autowired
    private GiftPaperObjectService giftPaperObjectService;

    @Override
    protected BaseService<GiftPaper, Long> getEntityService() {
        return giftPaperService;
    }

    @Override
    protected void checkEntityAclPermission(GiftPaper entity) {
        // TODO Add acl check code logic
    }

    @Override
    public void prepareEdit() {
        super.prepareEdit();
        if (bindingEntity.isNew()) {
            bindingEntity.setCode(giftPaperService.createUniqueCode());
            String passWord = StringUtils.remove(UUID.randomUUID().toString(), "-");
            bindingEntity.setPassword(passWord);
        }
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        return super.doSave();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    public void preparePaperDetailByTemplate() {
        String paperTemplateCode = getRequiredParameter("paperTemplateCode");
        if (bindingEntity.isNew()) {
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "code", paperTemplateCode));
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "paperMode", "G"));
            List<GiftPaper> giftPapers = giftPaperService.findByFilters(groupPropertyFilter);
            Assert.isTrue(giftPapers.size() == 1);
            GiftPaper giftPaperTemplate = giftPapers.get(0);
            bindingEntity.setCode(giftPaperService.createUniqueCode());
            String passWord = StringUtils.remove(UUID.randomUUID().toString(), "-");
            bindingEntity.setPassword(passWord);
            bindingEntity.setFaceValue(giftPaperTemplate.getFaceValue());
            bindingEntity.setFuncCode(giftPaperTemplate.getFuncCode());
            bindingEntity.setFuncParameter(giftPaperTemplate.getFuncParameter());
            bindingEntity.setBeginTime(giftPaperTemplate.getBeginTime());
            bindingEntity.setExpireTime(giftPaperTemplate.getExpireTime());
            bindingEntity.setTitle(giftPaperTemplate.getTitle());
            bindingEntity.setPaperSource(giftPaperTemplate.getPaperSource());
        } else if (paperTemplateCode.equals(bindingEntity.getPaperTemplateCode())) {
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "code", paperTemplateCode));
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "paperMode", "G"));
            List<GiftPaper> giftPapers = giftPaperService.findByFilters(groupPropertyFilter);
            Assert.isTrue(giftPapers.size() == 1);
            GiftPaper giftPaperTemplate = giftPapers.get(0);
            bindingEntity.setFaceValue(giftPaperTemplate.getFaceValue());
            bindingEntity.setFuncCode(giftPaperTemplate.getFuncCode());
            bindingEntity.setFuncParameter(giftPaperTemplate.getFuncParameter());
            bindingEntity.setBeginTime(giftPaperTemplate.getBeginTime());
            bindingEntity.setExpireTime(giftPaperTemplate.getExpireTime());
            bindingEntity.setTitle(giftPaperTemplate.getTitle());
            bindingEntity.setPaperSource(giftPaperTemplate.getPaperSource());
        }
    }

    public Map<String, String> getPaperTemplateMap() {
        Map<String, String> dataMap = new LinkedHashMap<String, String>();
        List<GiftPaper> giftPapers = giftPaperService.findPaperTemplates();
        for (GiftPaper item : giftPapers) {
            dataMap.put(item.getCode(), item.getTitle());
        }
        return dataMap;
    }

    @MetaData("使用范围对象")
    public HttpHeaders giftPaperR2Objects() {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "giftPaper", bindingEntity));
        List<GiftPaperObject> giftPaperObjects = giftPaperObjectService.findByFilters(groupPropertyFilter);
        setModel(buildPageResultFromList(giftPaperObjects));
        return buildDefaultHttpHeaders();
    }

    @MetaData("生成优惠券")
    public HttpHeaders creatGpBatch() throws NoSuchAlgorithmException, IOException {
        String pasDow = "";
        for (int i = 0; i < bindingEntity.getCounts(); i++) {
            GiftPaper giftPaper = new GiftPaper();
            String code = MD5.digest(UUID.randomUUID().toString());
            giftPaper.setCode(code.substring(4));
            String password = MD5.digest(UUID.randomUUID().toString());
            pasDow = pasDow + password.substring(4) + "\n";
            giftPaper.setPassword(password.substring(4));
            giftPaper.setPaperStatus(bindingEntity.getPaperStatus());
            giftPaper.setPaperMode("P");
            giftPaper.setTitle(bindingEntity.getTitle());
            giftPaper.setBeginTime(bindingEntity.getBeginTime());
            giftPaper.setCustomerProfile(bindingEntity.getCustomerProfile());
            giftPaper.setExpireTime(bindingEntity.getExpireTime());
            giftPaper.setFaceValue(bindingEntity.getFaceValue());
            giftPaper.setFuncCode(bindingEntity.getFuncCode());
            giftPaper.setFuncParameter(bindingEntity.getFuncParameter());
            giftPaper.setPaperSource(bindingEntity.getPaperSource());
            giftPaper.setOrderSeq(bindingEntity.getOrderSeq());
            giftPaper.setPaperTemplateCode(bindingEntity.getPaperTemplateCode());
            giftPaperService.save(giftPaper);
        }
        // 定义文件名格式并创建
//        File file = File.createTempFile("test", ".txt", new File("C:\\Users\\MYT\\Desktop"));
//        if (!file.exists()) {
//            file.mkdir();
//            System.out.println("文件夹已创建");
//        }
//        // 创建输出流
//        FileOutputStream outStream = new FileOutputStream(file);
//        // 得到二进制数据，以二进制封装得到数据，具有通用性
//        byte[] data = pasDow.getBytes();
//        // 写入数据
//        outStream.write(data);
//        // 关闭输出流
//        outStream.close();
        String result = "成功生成" + bindingEntity.getCounts() + "份优惠券";
        setModel(OperationResult.buildSuccessResult(result));
        return buildDefaultHttpHeaders();
    }

}